import { defineStore } from 'pinia';
import { api } from '@/services/api';
// RSA加密解密组件
import { JSEncrypt } from 'jsencrypt';

export const useJsencryptStore = defineStore('jsencrypt', () => {

    type EncryptInfo = {
        key: string;
        value: string;
    }
    
    /**
     * 数据加密
     * @param data 需要加密的数据
     */
    const encryptData = async (data: string): Promise<EncryptInfo> => {
        // 获取RSA算法公钥
        const response = await api.common.getPublicKey();
        // 新建JSEncrypt对象
        let encryptor = new JSEncrypt();
        // 设置公钥
        encryptor.setPublicKey(response.data.value);
        // 设置key
        let key: string = response.data.key;
        // 对密码进行加密
        let value: string = encryptor.encrypt(data).toString();
        return {
            key,
            value
        }
    }

    return {
        encryptData
    }
})